<?php
namespace api\components;

use Yii;
use yii\base\Exception;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\base\UserException;
use yii\web\HttpException;
use common\models\Client;
use yii\web\Response;
use Helper;

class ApiController extends \yii\web\Controller
{
    public $appkey = null;
    public $appInfo = null;
    public $appIp = '';
    public $os = 'web';

    public function beforeAction($action)
    {
        //var_dump($action->uniqueId);die;
        return true;
        Yii::$app->response->format = Response::FORMAT_JSON;
        if (Yii::$app->request->method == "GET") {
            $reqdata = Yii::$app->request->get();
        } else if (Yii::$app->request->method == "POST") {
            $reqdata = Yii::$app->request->post();
        } else {
            Yii::$app->response->data = ['message' => "ok", 'error' => 'ok', 'code' => 200, 'data' => []];
            return false;
        }
        $flag = false;
        $errorInfo = array('code' => '-2', 'message' => null, 'error' => null, 'data' => []);
        $header = Yii::$app->getRequest()->getHeaders();
        $sign = $header->get('FZM-Ca-Signature');
        $time = $header->get('FZM-Ca-Timestamp');
        $this->appkey = $header->get('FZM-Ca-AppKey');
        $appip = $header->get('FZM-Ca-AppIp');
        $os = $header->get('FZM-Ca-OS');
        $this->appIp = $appip;
        $this->os = $os;
        if (empty($time) || abs(time() - $time) >= Yii::$app->params['authTime']) {
            $errorInfo['message'] = "Timestamp is overtime";
        } else if (empty($this->appkey) || empty($sign)) {
            $errorInfo['message'] = "AppKey or Signature is empty";
        } else {
            $Client = Client::getClientCache($this->appkey);
            if ($Client) {
                $this->appInfo = $Client;
                $appSecret = Helper::decrypt($Client['appsecret'], Yii::$app->params['salt']);
                if (self::getSign($reqdata, $this->appkey, $appSecret, $time) != $sign) {
                    $errorInfo['message'] = "Signature is Error";
                } else if ($Client['statu'] != "1") {
                    $errorInfo['message'] = "AppKey Statu is Permission denied";
                } else if ($Client['allowip'] != '-1' && (strpos($Client['allowip'], $appip) === false)) {
                    $errorInfo['message'] = "Your Ip is Ban";
                } else {
                    $flag = true;
                }
            } else {
                $errorInfo['message'] = "AppKey is Error";
            }
        }
        if (Yii::$app->params['isDebug']) {
            $this->appInfo = Client::getClientCache($this->appkey);
            $flag = true;
        }
        if (!$flag) {
            $errorInfo['error'] = Yii::t('code', '-2');
            Yii::$app->response->data = $errorInfo;
            return false;
        }
        return true;
    }

    private static function getSign($params, $appkey, $appSecret, $time)
    {
        $sign = '';
        if (!empty($params)) {
            if (isset($params['r'])) unset($params['r']);
            if (isset($params['r'])) unset($params['r']);
            ksort($params);
            $string = http_build_query($params);
            $result = md5($appkey . $string . $appSecret . $time);
            $sign = strtoupper($result);
        }
        return $sign;
    }

    protected function initParams($p = [],$fields = [], $isFilter = false)
    {
        $params = [];
        if (!empty($fields)) {
            foreach ($fields as $key => $value) {
                if (isset($p[$value]) && (!empty($p[$value]) || $p[$value] == 0)) {
                    $params[$value] = $p[$value];
                } else {
                    if (!$isFilter) $params[$value] = null;
                }
            }
        }
        return $params;
    }

    public function message($code, $message = '', $data = array())
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $error = Yii::t('code', $code);
        if (empty($message)) $message = $error;
        return ['message' => $message, 'error' => $error, 'code' => $code, 'data' => $data];
    }

    public function actionError()
    {
        if (($exception = Yii::$app->getErrorHandler()->exception) === null) {
            $exception = new HttpException(404, Yii::t('yii', 'Page not found.'));
        }
        if ($exception instanceof HttpException) {
            $code = $exception->statusCode;
        } else {
            $code = $exception->getCode();
        }
        if ($exception instanceof UserException) {
            $message = $exception->getMessage();
        } else {
            $message = $this->defaultMessage ?: Yii::t('yii', 'An internal server error occurred.');
        }
        return ['message' => $message, 'code' => $exception->statusCode, 'error' => $exception, 'data' => []];
    }
}
